//
//  StreetController.swift
//  Swift-TableView-Example
//
//  Created by Bilal ARSLAN on 12/10/14.
//  Copyright (c) 2014 Bilal ARSLAN. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
import KeychainSwift

class StreetController: UIViewController, UITableViewDelegate, UITableViewDataSource, BMKLocationServiceDelegate, HttpProtocol {
    
    @IBOutlet weak var StreetsTableView: UITableView!
    
    let keychain = KeychainSwift(keyPrefix: "myTestKey_")
    let locService = BMKLocationService()
    
    var eHttp:HTTPController = HTTPController()
    
    var streets = [Street]()
    var tableData:[JSON]=[]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        eHttp.delegate = self
        
        StreetsTableView.delegate = self
        StreetsTableView.dataSource = self
        
        //取出当前用户位置附近的坐标
        //设置LBS
        locService.delegate = self
        locService.desiredAccuracy = kCLLocationAccuracyBest
        locService.distanceFilter = 10
        
        locService.startUserLocationService()
        
        //获取附近的用户
        let getUserUrl = "http://42.62.18.210:8090/apiradio/ar/getUsersByCity?userID="+keychain.get("registerUserID")!+"&lng="+keychain.get("registerlatitude")!+"&lat="+keychain.get("registerlongitude")!+"&page=1"
        print(getUserUrl)
        eHttp.onsearch(getUserUrl)
    }
    
    
    /* 获取街道数据的回调函数 */
    func didRecieveResults(results: AnyObject) {
        //print("results: \(results)")
        let json = JSON(results)
        
        if let channels = json["obj"]["positions"].array {
            print(channels)
        
            tableData = channels
            
            for var i = 0; i < tableData.count; i++
            {
                let rowData:JSON = tableData[i]
                // print(rowData["channelName"].string)
                if rowData["street"] == nil {
                    streets.append(Street(StreetName: "未知", MsgNum: String(rowData["count"])))
                }else {
                    streets.append(Street(StreetName: String(rowData["street"]), MsgNum: String(rowData["count"])))
                }
                
            }
            
            self.StreetsTableView!.reloadData()
        }
    }
    

    func didUpdateBMKUserLocation(userLocation: BMKUserLocation!) {
        print("--------------")
        print("\(userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude)")
        let test1 = userLocation.location.coordinate.latitude
        let test2 = userLocation.location.coordinate.longitude
        
        //对坐标进行存储,并且关闭
        //设置
        self.keychain.set(String(test1), forKey: "registerlatitude")
        self.keychain.set(String(test2), forKey: "registerlongitude")
        
        //self.locService.stopUserLocationService()
    }
    
    // MARK: - UITableView DataSource Methods
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifier: String = "StreetCell"
        
        var cell: StreetsListModel! = tableView.dequeueReusableCellWithIdentifier(identifier) as? StreetsListModel
        
        if cell == nil {
            cell = StreetsListModel(style: UITableViewCellStyle.Value1, reuseIdentifier: identifier)
        }
        
        cell.configurateTheCell(streets[indexPath.row])
        
        return cell!
    }
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return streets.count
    }
    
    //重构跳转页面函数
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "StreetCellToUser" {
            let indexPath = self.StreetsTableView!.indexPathForSelectedRow
            let destinationViewController: NearbyUser = segue.destinationViewController as! NearbyUser
            
            //print(streets[indexPath!.row].StreetNameStr)
            destinationViewController.StreetNameStr = streets[indexPath!.row].StreetNameStr

            //destinationViewController.imageName = recipes[indexPath!.row].thumbnails
        }
    }
    
    override func viewWillDisappear(animated: Bool) {
        print("----------------")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}